package com.innovation.chengzhangriji.service;

import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;

import com.google.gson.JsonElement;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;

public class DeleteTimelineService extends BaseSyncTimelineService {

    @Override
    protected void onTimelineStartCommand() {
        LoginInfo loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            stopSelf();
            return;
        }
        deleteTimeline(loginInfo);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void deleteTimeline(LoginInfo loginInfo) {
        int babyID = loginInfo.getBabyID();
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        final String uuid = DatabaseManager.getInstance(this).queryDeleteTimeline(babyID);
        if (!TextUtils.isEmpty(uuid)) {
            Client.requestDataDelete(this, phone, token, uuid, System.currentTimeMillis(), new ResponseHandler() {

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    super.onInnovationSuccess(value);
                    DatabaseManager.getInstance(DeleteTimelineService.this).deleteTimeline(uuid);
                    onTimelineStartCommand();
                }

            }, networkUnavailableSampleImpl());
        } else {
            stopSelf();
        }

    }
}
